﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Storage;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Storage
{
    public class AddStorageHandler : IRequestHandler<AddStorageCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<AddStorageHandler> logger;
        private readonly IMapper mapper;

        public AddStorageHandler(DatabaseContext db, ILogger<AddStorageHandler> logger, IMapper mapper)
        {
            this.db = db;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddStorageCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var storage = mapper.Map<StorageModel>(request);
            OperationModel operation=new OperationModel()
            {
                
                OperationName = request.LoginUserName,
                CreatTime = DateTime.Now,
                OTypeName = "添加",
                OperationSketch="添加了一条数据",
                IsDel = false
            };
            await db.SqlSugar.Insertable(operation).ExecuteCommandAsync();

            int r = await db.SqlSugar.Insertable(storage).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "工单仓库管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "工单仓库管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}